package com.surfilter.modules.user.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.surfilter.modules.user.dao.PermissionDao;
import com.surfilter.modules.user.dao.RoleDao;
import com.surfilter.modules.user.dao.UserDao;
import com.surfilter.modules.user.model.ActionModel;
import com.surfilter.modules.user.model.ModuleModel;
import com.surfilter.modules.user.model.RoleModel;
import com.surfilter.modules.user.model.UserModel;
import com.surfilter.modules.user.service.UserMgr;
import com.surfilter.platform.base.exception.CustomException;
import com.surfilter.platform.base.model.ActionPermission;
import com.surfilter.platform.base.model.Constants;
import com.surfilter.platform.base.model.PageInfo;
import com.surfilter.platform.base.model.ParameterClassType;
import com.surfilter.platform.base.model.ParameterInfo;
import com.surfilter.platform.base.model.ParameterMapper;
import com.surfilter.platform.base.model.PermissionMethodType;
import com.surfilter.platform.base.service.ServiceBase;
import com.surfilter.platform.base.service.ServiceContext;
import com.surfilter.platform.base.util.MD5;

@Service(value = Constants.SERVICE_USER)
public class UserMgrImpl extends ServiceBase implements UserMgr {

	@Resource
	private UserDao userDao;
	@Resource
	private RoleDao userRoleDao;
	@Resource
	private PermissionDao userPermissionDao;

	/************************************ USER START ****************************************/

	@ActionPermission(actionName = "addUser",remark = "添加用户", permission = PermissionMethodType.MODULE)
	@ParameterMapper({
			@ParameterInfo(mapName = "roleIds", index = 1, componentType = Integer.class, mapType = ParameterClassType.ARRAY),
			@ParameterInfo(mapName = "moduleIds", index = 2, componentType = Integer.class, mapType = ParameterClassType.ARRAY),
			@ParameterInfo(mapName = "actionIds", index = 3, componentType = Integer.class, mapType = ParameterClassType.ARRAY) })
	@Transactional(value="sufilter")
	public int addUser(UserModel userModel, List<Integer> roleIds,
			List<Integer> moduleIds, List<Integer> actionIds,
			HttpServletRequest request) {
		UserModel reUser = userDao.getUserByName(userModel);
		if (reUser != null)
			throw new CustomException("用户名重复，修改用户名后添加");
		int sessionUserId = ServiceContext.getUserIdInSession(request);
		Date updateTime = new Date();
		userModel.setCreateUser(sessionUserId);
		userModel.setCreateTime(updateTime);
		userModel.setUpdateUser(sessionUserId);
		userModel.setUpdateTime(updateTime);
		userModel.setPassword(MD5.encode(userModel.getUserName()));
		int userId = userDao.addUser(userModel);
		this.updateUserRoles(userId, roleIds, sessionUserId, updateTime);
		this.updatePermissionModules(userId, moduleIds, sessionUserId,
				updateTime);
		this.updatePermissionActions(userId, actionIds, sessionUserId,
				updateTime);
		return userId;
	}

	@ActionPermission(actionName = "delUser",remark = "删除用户", permission = PermissionMethodType.MODULE)
	@Transactional(value="sufilter")
	public void delUser(UserModel userModel, HttpServletRequest request) {
		userDao.delUser(userModel);
	}

	@ActionPermission(actionName = "chgUser",remark = "更改用户", permission = PermissionMethodType.MODULE)
	@ParameterMapper({
			@ParameterInfo(mapName = "roleIds", index = 1, componentType = Integer.class, mapType = ParameterClassType.ARRAY),
			@ParameterInfo(mapName = "moduleIds", index = 2, componentType = Integer.class, mapType = ParameterClassType.ARRAY),
			@ParameterInfo(mapName = "actionIds", index = 3, componentType = Integer.class, mapType = ParameterClassType.ARRAY) })
	@Transactional(value="sufilter")
	public void chgUser(UserModel userModel, List<Integer> roleIds,
			List<Integer> moduleIds, List<Integer> actionIds,
			HttpServletRequest request) {
		int userId = userModel.getId();
		int sessionUserId = ServiceContext.getUserIdInSession(request);
		Date updateTime = new Date();
		userModel.setUpdateUser(sessionUserId);
		userModel.setUpdateTime(updateTime);
		userDao.chgUser(userModel);
		this.updateUserRoles(userId, roleIds, sessionUserId, updateTime);
		this.updatePermissionModules(userId, moduleIds, sessionUserId,
				updateTime);
		this.updatePermissionActions(userId, actionIds, sessionUserId,
				updateTime);
	}

	@ActionPermission(actionName = "getUsers",remark = "获取所有用户", permission = PermissionMethodType.MODULE)
	public List<UserModel> getUsers(UserModel userModel,
			HttpServletRequest request) {
		PageInfo pageInfo = PageInfo.getPageInfo(request);
		return userDao.getUsers(userModel, pageInfo);
	}

	@ActionPermission(actionName = "getUsersCount",remark = "获取用户数量", permission = PermissionMethodType.NONE)
	public int getUsersCount(UserModel userModel) {
		return userDao.getUsersCount(userModel);
	}
	
	@Transactional(value="sufilter")
	@ActionPermission(actionName = "delUsers",remark = "删除用户", permission = PermissionMethodType.MODULE)
	@ParameterMapper({ @ParameterInfo(mapName = "userIds", componentType = Integer.class, index = 0, mapType = ParameterClassType.ARRAY) })
	public boolean delUsers(List<Integer> userIds,HttpServletRequest request,HttpServletResponse response) throws CustomException {
		int sessionUserId = ServiceContext.getUserIdInSession(request);
		if(userIds.contains(sessionUserId)){
			throw new CustomException("不能删除自己");
		}
//		userDao.delUsers(userIds);
		return true;
	}

	/************************************ USER END ****************************************/

	/************************************ ROLE START ****************************************/

	@ActionPermission(actionName = "getNotUserRoles",remark = "获取角色下所有用户", permission = PermissionMethodType.MODULE)
	@ParameterMapper(@ParameterInfo(mapName = "userId", index = 0))
	public List<RoleModel> getNotUserRoles(Integer userId) {
		return userRoleDao.getNotUserRoles(userId);
	}

	@ActionPermission(actionName = "getUserRoles",remark = "获取用户角色", permission = PermissionMethodType.MODULE)
	@ParameterMapper(@ParameterInfo(mapName = "userId", index = 0))
	public List<RoleModel> getUserRoles(Integer userId) {
		if (userId == null)
			return null;
		return userRoleDao.getUserRoles(userId);
	}

	/**
	 * updateUserRoles: 1.Delete All User's Roles 2.Insert All User's Roles
	 * */
	private boolean updateUserRoles(int userId, List<Integer> roleIds,
			int updateUser, Date updateTime) {
		userRoleDao.delAllUserRoles(userId);
		if (roleIds != null && roleIds.size() > 0)
			userRoleDao
					.addAllUserRoles(userId, roleIds, updateUser, updateTime);
		return true;
	}

	// TODO:角色模块使用的方法，需要移除
	@ActionPermission(actionName = "getRoleUsers",remark = "获取角色下所有用户", permission = PermissionMethodType.MODULE)
	@ParameterMapper(@ParameterInfo(mapName = "roleId", index = 0))
	public List<UserModel> getRoleUsers(int roleId) {
		return userDao.getUserByRoleId(roleId);
	}
	
	@Transactional(value="sufilter")
	@ActionPermission(actionName = "changeUserPwd",remark = "更改密码", permission = PermissionMethodType.NONE)
	public void changeUserPwd(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HttpSession session = request.getSession();
		com.surfilter.platform.data.model.UserModel  user = (com.surfilter.platform.data.model.UserModel )session.getAttribute(Constants.LOGIN_USER_TAG);
		if(user == null){
			throw new CustomException("用户未登陆");
		}else{
			String oldPass = request.getParameter("oldPass");
			String newPass = request.getParameter("newPass");
			UserModel nowUser = userDao.getUserByID(user.getId());
			if(MD5.encode(oldPass).equals(nowUser.getPassword())){
				nowUser.setPassword(MD5.encode(newPass));
				userDao.chgUserPwd(nowUser);
			}else{
				throw new CustomException("原始密码输入错误");
			}
		}
	}

	/************************************ ROLE END ****************************************/

	/************************************ PERMISSION START ****************************************/
	@ActionPermission(actionName = "getUserValidModulesAndActionsForAuthTree",remark = "获取用户权限树", permission = PermissionMethodType.MODULE)
	@ParameterMapper(@ParameterInfo(mapName = "userId", index = 0))
	public List<ModuleModel> getUserValidModulesAndActionsForAuthTree(
			Integer userId) {
		List<ModuleModel> modules = userPermissionDao.getAllValidModules();
		if (modules == null || modules.size() == 0)
			return modules;
		List<Integer> perModules = null;
		List<Integer> perActions = null;
		if (userId != null) {
			perModules = userPermissionDao.getModuleIdByUserId(userId);
			perActions = userPermissionDao.getActionIdByUserId(userId);
		}
		for (ModuleModel module : modules) {
			Integer moduleId = module.getId();
			List<ActionModel> actions = userPermissionDao
					.getActionsByModuleId(moduleId);
			module.setActionModels(actions);
			if (perModules != null && perModules.contains(moduleId)) {
				module.setChecked(true);
			} else {
				continue;
			}
			if (perActions != null && perActions.size() > 0) {
				for (ActionModel action : actions) {
					if (perActions.contains(action.getId())) {
						action.setChecked(true);
					}
				}
			}
		}
		return modules;
	}

	/**
	 * updatePermissionModules 1.delete all user's permission modules 2.add all
	 * user's permission modules
	 * */
	private boolean updatePermissionModules(int userId,
			List<Integer> moduleIds, int updateUser, Date updateTime) {
		userPermissionDao.delAllUserModules(userId);
		if (moduleIds != null && moduleIds.size() > 0)
			userPermissionDao.addAllUserModules(userId, moduleIds, updateUser,
					updateTime);
		return true;
	}

	/**
	 * updatePermissionActions 1.delete all user's permission actions 2.add all
	 * user's permission actions
	 * */
	private boolean updatePermissionActions(int userId,
			List<Integer> actionIds, int updateUser, Date updateTime) {
		userPermissionDao.delAllUserActions(userId);
		if (actionIds != null && actionIds.size() > 0)
			userPermissionDao.addAllUserActions(userId, actionIds, updateUser,
					updateTime);
		return true;
	}
	
	/************************************ PERMISSION END ****************************************/
}
